package com.xbongbong.paas.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xbongbong.i18n.util.I18nMessageUtil;
import com.xbongbong.paas.constant.PaasConstant;
import com.xbongbong.paas.domain.entity.PaasAppEntity;
import com.xbongbong.paas.domain.entity.PaasMenuEntity;
import com.xbongbong.paas.domain.entity.ext.PaasFormEntityExt;
import com.xbongbong.paas.enums.DelEnum;
import com.xbongbong.paas.help.CommonHelp;
import com.xbongbong.paas.help.team.FormTeamSetHelp;
import com.xbongbong.paas.log.MongoLogHelp;
import com.xbongbong.paas.log.constant.LogMemoConstant;
import com.xbongbong.paas.model.PaasAppModel;
import com.xbongbong.paas.model.PaasFormExplainModel;
import com.xbongbong.paas.model.PaasFormModel;
import com.xbongbong.paas.model.PaasMenuModel;
import com.xbongbong.paas.service.FormTeamSetService;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.util.BeanUtil;
import com.xbongbong.paas.toolbox.util.CollectionsUtil;
import com.xbongbong.paas.toolbox.util.DateTimeUtil;
import com.xbongbong.paas.toolbox.wrap.UserVO;
import com.xbongbong.pro.domain.entity.FormLabelEntity;
import com.xbongbong.pro.domain.entity.FormTeamSetEntity;
import com.xbongbong.pro.domain.entity.UpdateDataEntity;
import com.xbongbong.pro.enums.PackageTypeEnum;
import com.xbongbong.pro.enums.SaasMarkEnum;
import com.xbongbong.pro.enums.errorcodes.SystemErrorCodeEnum;
import com.xbongbong.pro.enums.errorcodes.UserTeamErrorCodeEnum;
import com.xbongbong.pro.enums.permission.enums.ProPermissionAliasEnum;
import com.xbongbong.pro.enums.teammembers.enums.FormDefaultPatternEnum;
import com.xbongbong.pro.enums.teammembers.enums.FormPatternEnum;
import com.xbongbong.pro.formteamset.dto.FormTeamSetDetailDTO;
import com.xbongbong.pro.formteamset.dto.FormTeamSetLinkFormEnableDTO;
import com.xbongbong.pro.formteamset.dto.FormTeamSetLinkFormListDTO;
import com.xbongbong.pro.formteamset.dto.FormTeamSetSaveDTO;
import com.xbongbong.pro.formteamset.vo.FormTeamSetDetailVO;
import com.xbongbong.pro.formteamset.vo.FormTeamSetLinkFormEnableVO;
import com.xbongbong.pro.formteamset.vo.FormTeamSetLinkFormListVO;
import com.xbongbong.pro.formteamset.vo.FormTeamSetSaveVO;
import com.xbongbong.pro.label.pojo.LabelPojo;
import com.xbongbong.pro.log.pojo.DetailLogPojo;
import com.xbongbong.pro.model.FormLabelModel;
import com.xbongbong.pro.model.FormTeamSetModel;
import com.xbongbong.pro.team.TeamLinkPOJO;
import com.xbongbong.saas.constant.BasicConstant;
import com.xbongbong.saas.constant.ParameterConstant;
import com.xbongbong.saas.constant.teammembers.TeamMembersConstant;
import com.xbongbong.saas.domain.entity.WorkOrderFormEntity;
import com.xbongbong.saas.enums.FormTeamSetEnum;
import com.xbongbong.saas.enums.OperateModuleTypeEnum;
import com.xbongbong.saas.enums.OperateTypeEnum;
import com.xbongbong.saas.enums.XbbRefTypeEnum;
import com.xbongbong.saas.model.WorkOrderFormModel;
import com.xbongbong.saas.service.toolbox.help.LogHelp;
import com.xbongbong.saas.service.toolbox.help.UserTeamHelp;
import com.xbongbong.sys.help.ProPermissionHelp;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.MapUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;

/**
 *
 * @author 魏荣杰
 *
 */
@Service("formTeamSetService")
@Slf4j
public class FormTeamSetServiceImpl implements FormTeamSetService {

    @Resource
    private FormTeamSetModel formTeamSetModel;
    @Resource
    private FormLabelModel formLabelModel;
    @Resource
    private PaasAppModel paasAppModel;
    @Resource
    private PaasMenuModel paasMenuModel;
    @Resource
    private PaasFormModel paasFormModel;
    @Resource
    private WorkOrderFormModel workOrderFormModel;
    @Resource
    private MongoLogHelp mongoLogHelp;
    @Resource
    private LogHelp logHelp;
    @Resource
    private PaasFormExplainModel paasFormExplainModel;
    @Resource
    private CommonHelp commonHelp;
    @Resource
    private UserTeamHelp userTeamHelp;
    @Resource
    private FormTeamSetHelp formTeamSetHelp;

    @Override
    public FormTeamSetDetailVO detail(FormTeamSetDetailDTO formTeamSetDetailDTO) throws XbbException {
        String corpid = formTeamSetDetailDTO.getCorpid();
        Long formId = formTeamSetDetailDTO.getFormId();
        Integer businessType = formTeamSetDetailDTO.getBusinessType();

        UserVO loginUser = formTeamSetDetailDTO.getLoginUser();
        if (!ProPermissionHelp.hasPermission(loginUser, ProPermissionAliasEnum.FORM_SET_VIEW.getAlias())) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100050.getCode(), String.format(SystemErrorCodeEnum.API_ERROR_100050.getMsg(), ProPermissionAliasEnum.FORM_SET_VIEW.getMemo()));
        }

        Integer feeType = commonHelp.getCurrentCompanyPackage(corpid);
        FormTeamSetDetailVO formTeamSetDetailVO = new FormTeamSetDetailVO();
        //表单设置-》只有旗舰版才会有团队成员设置、数据共享/隔离设置；高级版、旗舰版才会有继承列表设置，高级版只能删除选到的列表，旗舰版可以增加删除列表（后面逻辑交给前端处理）
        boolean linkAble = FormTeamSetEnum.checkLinkAble(feeType, businessType);
        if (Objects.equals(feeType, PackageTypeEnum.ULTIMATE.getType())) {
            formTeamSetDetailVO.setLabelsEnable(true);
            //bom清单、供应商联系人、paas表单不支持共享隔离切换
            if(Objects.equals(businessType,XbbRefTypeEnum.BOM_BILL.getCode())
                    || Objects.equals(businessType,XbbRefTypeEnum.SUPPLIER_CONTACT.getCode())
                    || Objects.equals(businessType,XbbRefTypeEnum.RECEIPT_ORDER.getCode())
                    || Objects.equals(businessType,XbbRefTypeEnum.WORK_ORDER_V2.getCode())
                    || Objects.equals(formTeamSetDetailDTO.getSaasMark(), SaasMarkEnum.PAAS.getCode())){
                formTeamSetDetailVO.setModelEnable(false);
            }else{
                formTeamSetDetailVO.setModelEnable(true);
            }
            formTeamSetDetailVO.setLinkFormsEnable(linkAble);
        }else if (Objects.equals(feeType, PackageTypeEnum.ADVANCED.getType())) {
            formTeamSetDetailVO.setLinkFormsEnable(linkAble);
        }
        FormTeamSetEntity formTeamSetEntity = formTeamSetHelp.getFormTeamSet(corpid, formId, formTeamSetDetailDTO.getSaasMark(), businessType, formTeamSetDetailDTO.getDistributorMark());
        formTeamSetDetailVO.setId(formTeamSetEntity.getId());
        formTeamSetDetailVO.setFormId(formTeamSetEntity.getFormId());
        formTeamSetDetailVO.setSaasMark(formTeamSetEntity.getSaasMark());
        formTeamSetDetailVO.setBusinessType(formTeamSetEntity.getBusinessType());
        formTeamSetDetailVO.setDistributorMark(formTeamSetEntity.getDistributorMark());
        formTeamSetDetailVO.setPublicSwitch(formTeamSetEntity.getPublicSwitch());
        if ( Objects.equals(feeType,BasicConstant.THREE) && !Objects.isNull(formTeamSetEntity.getModel())) {
            formTeamSetDetailVO.setModel(formTeamSetEntity.getModel());
            //旗舰版，隔离模式不放出继承列表  （高级版的继承列表设置在formTeamSetHelp根据套餐版本处理过）
            if(Objects.equals(formTeamSetEntity.getModel(),FormPatternEnum.FORM_ISOLATION.getModel())){
                formTeamSetDetailVO.setLinkFormsEnable(false);
            }
        }
        JSONArray labelArray = formTeamSetEntity.getLabelId();
        List<Long> labelIds = labelArray.toJavaList(Long.class);
        List<FormLabelEntity> formLabelEntities = formLabelModel.getByLabelIdIn(corpid, labelIds);

        List<LabelPojo> labels = new ArrayList<>();
        formLabelEntities.forEach(v -> labels.add(new LabelPojo(v.getId(), v.getColor(), v.getName())));

        formTeamSetDetailVO.setLabels(labels);

        if (!Objects.isNull(formTeamSetEntity.getLinkForm())) {
            List<TeamLinkPOJO> teamLinkPOJOS = JSON.parseArray(JSON.toJSONString(formTeamSetEntity.getLinkForm()), TeamLinkPOJO.class);

            // 过滤掉未开启和关闭的应用的相关表单
//            filterUnenableAppAndForm(corpid, teamLinkPOJOS);

            formTeamSetDetailVO.setLinkForms(teamLinkPOJOS);
        }

        formTeamSetDetailVO.setLabelManage(loginUser.getPermSet().contains(ProPermissionAliasEnum.FORM_SET_UPDATE.getAlias()));
        return formTeamSetDetailVO;
    }

    @Override
    public FormTeamSetSaveVO save(FormTeamSetSaveDTO formTeamSetSaveDTO) throws XbbException {

        UserVO loginUser = formTeamSetSaveDTO.getLoginUser();
        if (!loginUser.getPermSet().contains(ProPermissionAliasEnum.FORM_SET_UPDATE.getAlias())) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100050.getCode(), String.format(SystemErrorCodeEnum.API_ERROR_100050.getMsg(), ProPermissionAliasEnum.FORM_SET_UPDATE.getMemo()));
        }

        String corpid = formTeamSetSaveDTO.getCorpid();
        Long id = formTeamSetSaveDTO.getId();
        Long formId = formTeamSetSaveDTO.getFormId();
        Integer saasMark = formTeamSetSaveDTO.getSaasMark();
        Integer businessType = formTeamSetSaveDTO.getBusinessType();
        Integer distributorMark = formTeamSetSaveDTO.getDistributorMark();
        Integer model = formTeamSetSaveDTO.getModel();
        Integer publicSwitch = formTeamSetSaveDTO.getPublicSwitch();
        Integer feeType = commonHelp.getCurrentCompanyPackage(corpid);
        List<LabelPojo> labels = formTeamSetSaveDTO.getLabels();
        List<TeamLinkPOJO> linkForms = Objects.isNull(formTeamSetSaveDTO.getLinkForms()) ? new ArrayList<>() : formTeamSetSaveDTO.getLinkForms();
        JSONArray linkFormsJsonArray = JSON.parseArray(JSON.toJSONString(linkForms));
        List<Long> labelIds = new ArrayList<>();
        labels.forEach(v -> labelIds.add(v.getId()));


        FormTeamSetEntity formTeamSetEntity;
        FormTeamSetEntity formTeamSetEntityOld = new FormTeamSetEntity();
        long now = DateTimeUtil.getInt();
        if(Objects.isNull(model)){
            model = FormDefaultPatternEnum.getModelValueByBusinessType(businessType);
        }
        if (Objects.equals(id, 0L)) {
            // 新建
            formTeamSetEntity = new FormTeamSetEntity();
            formTeamSetEntity.setCorpid(corpid);
            formTeamSetEntity.setFormId(formId);
            formTeamSetEntity.setBusinessType(businessType);
            formTeamSetEntity.setSaasMark(saasMark);
            formTeamSetEntity.setDistributorMark(distributorMark);

            formTeamSetEntity.setModel(model);
            formTeamSetEntity.setPublicSwitch(publicSwitch);
            formTeamSetEntity.setLabelId(JSON.parseArray(JSON.toJSONString(labelIds)));
            formTeamSetEntity.setLinkForm(linkFormsJsonArray);

            formTeamSetEntity.setAddTime(now);
            formTeamSetEntity.setUpdateTime(now);
            formTeamSetEntity.setDel(DelEnum.NORMAL.getDel());
        } else {
            //编辑
            //编辑这一层有个特殊逻辑，比如高级版在继承列表展示的时候隐藏掉，直接拿前端给的继承列表会漏掉一些业务，所以需要数据库的与前端传的进行一个组合
            formTeamSetEntity = formTeamSetModel.getByKey(id, corpid);
            boolean ultimateTag = Objects.equals(feeType, PackageTypeEnum.ULTIMATE.getType());
            if (!ultimateTag) {
                List<Integer> linkList = FormTeamSetEnum.getBusLinkList(businessType, ultimateTag, false);
                JSONArray dbLinkForms = formTeamSetEntity.getLinkForm();
                JSONArray lessLinkForms = new JSONArray();
                for (int i = 0; i < dbLinkForms.size(); i++) {
                    JSONObject dbLinkJson = dbLinkForms.getJSONObject(i);
                    Integer linkBusinessType = dbLinkJson.getInteger(TeamMembersConstant.LINK_BUSINESS_TYPE_KEY);
                    if (CollectionUtils.isNotEmpty(linkList) && !linkList.contains(linkBusinessType)) {
                        lessLinkForms.add(dbLinkJson);
                    }
                }
                if (Objects.nonNull(lessLinkForms) && lessLinkForms.size() > BasicConstant.ZERO) {
                    linkFormsJsonArray.addAll(lessLinkForms);
                }
            }

            BeanUtil.copyProperties(formTeamSetEntity,formTeamSetEntityOld);
            if (Objects.isNull(formTeamSetEntity)) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100404);
            }
            formTeamSetEntity.setModel(model);
            formTeamSetEntity.setPublicSwitch(publicSwitch);
            formTeamSetEntity.setLabelId(JSON.parseArray(JSON.toJSONString(labelIds)));
            formTeamSetEntity.setLinkForm(linkFormsJsonArray);

            formTeamSetEntity.setUpdateTime(now);
        }

        //客户最多关联6个业务，其余表单最多关联5个业务
        if(Objects.equals(businessType,XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode())){

            if(linkFormsJsonArray.size() > TeamMembersConstant.CUSTOMER_LINK_LIMIT){
                throw new XbbException(UserTeamErrorCodeEnum.API_ERROR_271006);
            }

        }else{

            if(linkFormsJsonArray.size() > TeamMembersConstant.OTHER_LINK_LIMIT){
                throw new XbbException(UserTeamErrorCodeEnum.API_ERROR_271005);
            }
        }

        formTeamSetModel.save(formTeamSetEntity);

        //修改model要同步到其他模板
        HashMap<String, Object> params = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        params.put(ParameterConstant.CORPID,corpid);
        params.put(ParameterConstant.BUSINESS_TYPE,businessType);
        params.put(ParameterConstant.DEL,DelEnum.NORMAL);

        List<PaasFormEntityExt> paasFormEntityExtList = paasFormModel.findEntitys(params);
        List<Long> formIdList = paasFormEntityExtList.stream().map(PaasFormEntityExt::getId).collect(Collectors.toList());
        //记录已经设置过的表单 id -> formId
        Map<Long,Long> hasSettings = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        List<FormTeamSetEntity> formTeamSetList = formTeamSetHelp.getFormTeamSetList(corpid, formIdList, saasMark, businessType, distributorMark);

        for (FormTeamSetEntity teamSetEntity : formTeamSetList) {
            teamSetEntity.setModel(model);
            //保存过设置才会有数据库的id
            if(!Objects.equals(teamSetEntity.getId(), BasicConstant.ZERO_LONG) && !Objects.equals(teamSetEntity.getFormId(),formId)){
                hasSettings.put(teamSetEntity.getId(),teamSetEntity.getFormId());
            }
        }

        //走update
        if(MapUtils.isNotEmpty(hasSettings)){
            List<UpdateDataEntity> updateDataEntities = new ArrayList<>();
            Integer finalModel = model;
            hasSettings.entrySet().forEach(v -> {
                UpdateDataEntity updateDataEntity = new UpdateDataEntity();
                updateDataEntity.setUpdateTime(now);
                updateDataEntity.setId(v.getKey());
                updateDataEntity.setCorpid(corpid);
                updateDataEntity.setModel(finalModel);
                updateDataEntities.add(updateDataEntity);
            });
            formTeamSetModel.updateBatch(updateDataEntities,corpid);
        }

        //走insert
        List<FormTeamSetEntity> insertList = formTeamSetList.stream().filter(v -> !hasSettings.values().contains(v.getFormId()) && !Objects.equals(v.getFormId(),formId)).collect(Collectors.toList());
        if(CollectionUtils.isNotEmpty(insertList)){
            formTeamSetModel.insertBatch(insertList);
        }


        //日志
        PaasFormEntityExt passForm = paasFormModel.getByKey(formTeamSetSaveDTO.getFormId(), corpid);
        String memo = String.format(I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_FORM_LABEL_SEETINGS),loginUser.getName(),passForm.getName());
        List<DetailLogPojo> detailArr = changeFormTeamSetLog(formTeamSetEntityOld, formTeamSetEntity, corpid, businessType, formTeamSetSaveDTO, feeType);
        mongoLogHelp.buildLog4DetailArr(detailArr,corpid,loginUser.getUserId(),loginUser.getName(), OperateModuleTypeEnum.RESPONSIBLE_TEAM, OperateTypeEnum.FORM_LABEL_SETTINGS,passForm.getId().toString(),passForm.getName(),memo,formTeamSetSaveDTO.getHttpHeader());
        FormTeamSetSaveVO formTeamSetSaveVO = new FormTeamSetSaveVO();
        formTeamSetSaveVO.setId(formTeamSetEntity.getId());
        return formTeamSetSaveVO;
    }

    /**
     * 更新团队成员表单设置日志记录
     * 旗舰版所有设置都有；高级版：成员继承设置； 标准版：啥都没有
     *
     * @param oldFormTeamSetEntity 老的团队成员设置
     * @param newFormTeamSetEntity 新的团队成员设置
     * @param corpid 公司id
     * @param feeType 套餐版本
     */
    private List<DetailLogPojo> changeFormTeamSetLog(FormTeamSetEntity oldFormTeamSetEntity, FormTeamSetEntity newFormTeamSetEntity, String corpid,
                                      Integer businessType, FormTeamSetSaveDTO formTeamSetSaveDTO, Integer feeType) {
        List<DetailLogPojo> detailArr = new ArrayList<>();
        //成员标签-日志
        //老标签
        if (Objects.equals(PackageTypeEnum.ULTIMATE.getType(), feeType)) {
            JSONArray oldLabelIdArray =  Objects.isNull(oldFormTeamSetEntity.getLabelId()) ? new JSONArray() : oldFormTeamSetEntity.getLabelId();
            List<Long> oldLabelIds = oldLabelIdArray.toJavaList(Long.class);
            List<FormLabelEntity> oldLabels = formLabelModel.getByLabelIdIn(corpid, oldLabelIds);
            StringBuffer oldLabelStr = new StringBuffer();
            oldLabels.forEach(oldFormLabelEntity -> {
                oldLabelStr.append(oldFormLabelEntity.getName()).append(",");
            });
            if (Objects.nonNull(oldLabelStr) && !Objects.equals("", oldLabelStr.toString())) {
                oldLabelStr.deleteCharAt(oldLabelStr.length() - 1);
            }
            //新标签
            List<LabelPojo> labels = Objects.isNull(formTeamSetSaveDTO.getLabels()) ? new ArrayList<>() : formTeamSetSaveDTO.getLabels();
            StringBuffer newLabelStr = new StringBuffer();
            labels.forEach(labelPojo -> {
                newLabelStr.append(labelPojo.getName()).append(",");
            });
            if (Objects.nonNull(newLabelStr) && !Objects.equals("", newLabelStr.toString())) {
                newLabelStr.deleteCharAt(newLabelStr.length() - 1);
            }
            DetailLogPojo labelDetailLogPojo = new DetailLogPojo(I18nMessageUtil.getMessage(TeamMembersConstant.MEMBER_LABELS), oldLabelStr.toString(), newLabelStr.toString());
            detailArr.add(labelDetailLogPojo);
        }

        //数据共享/隔离设置-日志
        if (Objects.equals(PackageTypeEnum.ULTIMATE.getType(), feeType) && Objects.equals(newFormTeamSetEntity.getSaasMark(), SaasMarkEnum.SAAS.getCode())) {
            Integer oldModel = oldFormTeamSetEntity.getModel();
            String oldModelStr = null;
            Integer newModel = newFormTeamSetEntity.getModel();
            String newModelStr = null;
            if (Objects.isNull(oldModel)) {
                oldModel = FormDefaultPatternEnum.getModelValueByBusinessType(businessType);
            }
            if (Objects.equals(FormPatternEnum.FORM_SHARE.getModel(), oldModel)) {
                oldModelStr = I18nMessageUtil.getMessage(TeamMembersConstant.DATA_SHARING);
            }else {
                oldModelStr = I18nMessageUtil.getMessage(TeamMembersConstant.ISOLATION_SHARING);
            }
            if (Objects.equals(FormPatternEnum.FORM_SHARE.getModel(), newModel)) {
                newModelStr = I18nMessageUtil.getMessage(TeamMembersConstant.DATA_SHARING);
            }else {
                newModelStr = I18nMessageUtil.getMessage(TeamMembersConstant.ISOLATION_SHARING);
            }
            DetailLogPojo dataShareIsoDetailLogPojo = new DetailLogPojo(I18nMessageUtil.getMessage(TeamMembersConstant.DATA_SHARING_OR_ISOLATION_SETTING), oldModelStr, newModelStr);
            detailArr.add(dataShareIsoDetailLogPojo);
        }

        //继承列表设置-日志
        //调整前列表集
        boolean linkAble = FormTeamSetEnum.checkLinkAble(feeType, businessType);
        if (linkAble) {
            JSONArray oldLinkFormJsonArray = Objects.isNull(oldFormTeamSetEntity.getLinkForm()) ? new JSONArray() : oldFormTeamSetEntity.getLinkForm();
            List<TeamLinkPOJO> oldTeamLinkList = JSON.parseArray(JSON.toJSONString(oldLinkFormJsonArray), TeamLinkPOJO.class);
            StringBuffer oldLinkFormStr = new StringBuffer();
            oldTeamLinkList.forEach(oldTeamLinkPOJO -> {
                oldLinkFormStr.append(oldTeamLinkPOJO.getName()).append(",");
            });
            if (Objects.nonNull(oldLinkFormStr) && !Objects.equals("", oldLinkFormStr.toString())) {
                oldLinkFormStr.deleteCharAt(oldLinkFormStr.length() - 1);
            }

            //调整后继承列表集
            JSONArray newLinkFormJsonArray = Objects.isNull(newFormTeamSetEntity.getLinkForm()) ? new JSONArray() : newFormTeamSetEntity.getLinkForm();
            List<TeamLinkPOJO> newTeamLinkList = JSON.parseArray(JSON.toJSONString(newLinkFormJsonArray), TeamLinkPOJO.class);
            StringBuffer newLinkFormStr = new StringBuffer();
            newTeamLinkList.forEach(newTeamLinkPOJO -> {
                newLinkFormStr.append(newTeamLinkPOJO.getName()).append(",");
            });
            if (Objects.nonNull(newLinkFormStr) && !Objects.equals("", newLinkFormStr.toString())) {
                newLinkFormStr.deleteCharAt(newLinkFormStr.length() - 1);
            }
            DetailLogPojo linkFormDetailLogPojo = new DetailLogPojo(I18nMessageUtil.getMessage(TeamMembersConstant.LINK_FORM_SETTING), oldLinkFormStr.toString(), newLinkFormStr.toString());
            detailArr.add(linkFormDetailLogPojo);
        }

        //更新时间
        userTeamHelp.getStringTime(oldFormTeamSetEntity.getUpdateTime(), DateTimeUtil.getInt(), detailArr);
        return detailArr;
    }

    @Override
    public FormTeamSetLinkFormListVO linkFormList(FormTeamSetLinkFormListDTO formTeamSetLinkFormListDTO) throws XbbException {
        // 选择关联列表列表
        //只有默认关联的列表可以编辑共享/隔离模式，自定义关联表单默认隔离，不参与设置

        String corpid = formTeamSetLinkFormListDTO.getCorpid();
        Integer businessType = formTeamSetLinkFormListDTO.getBusinessType();
        List<TeamLinkPOJO> linkFormList ;
        XbbRefTypeEnum xbbRefTypeEnum = XbbRefTypeEnum.getByCode(businessType);
        Integer saasMark = formTeamSetLinkFormListDTO.getSaasMark();
        Integer distributorMark = formTeamSetLinkFormListDTO.getDistributorMark();
        Map<String,Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        param.put(ParameterConstant.CORPID, corpid);
        param.put("distributorMark",distributorMark);
        param.put("saasMark", saasMark);
        Integer feeType = commonHelp.getCurrentCompanyPackage(corpid);
        boolean ultimateTag = Objects.equals(feeType, PackageTypeEnum.ULTIMATE.getType());
        List<Integer> linkList = FormTeamSetEnum.getBusLinkList(businessType, ultimateTag, false);
        param.put("businessTypeList",linkList);
        List<PaasFormEntityExt> formEntitys = paasFormModel.findEntitys(param);
        List<TeamLinkPOJO> teamLinkPOJOList = new ArrayList<>();
        //将PaasFormEntityExt封装成TeamLinkPojo
        formEntitys.forEach(v -> teamLinkPOJOList.add(getTeamLinkPojo(v)));
        // 过滤掉未启用的应用和表单
        filterUnenableAppAndForm(corpid,formEntitys);
        linkFormList = formatLinkFormList(formEntitys, xbbRefTypeEnum, saasMark, distributorMark, linkList);
        FormTeamSetLinkFormListVO formTeamSetLinkFormListVO = new FormTeamSetLinkFormListVO();
        formTeamSetLinkFormListVO.setLinkFormList(linkFormList);
        return formTeamSetLinkFormListVO;
    }


    @Override
    public FormTeamSetLinkFormEnableVO linkFormEnable(FormTeamSetLinkFormEnableDTO formTeamSetLinkFormEnableDTO) throws XbbException {
        FormTeamSetLinkFormEnableVO formTeamSetLinkFormEnableVO = new FormTeamSetLinkFormEnableVO();
        String corpid = formTeamSetLinkFormEnableDTO.getCorpid();
        Integer businessType = formTeamSetLinkFormEnableDTO.getBusinessType();
        Integer model = formTeamSetLinkFormEnableDTO.getModel();
        Integer feeType = commonHelp.getCurrentCompanyPackage(corpid);
        //表单设置-》只有旗舰版才会有团队成员设置、数据共享/隔离设置；高级版、旗舰版才会有继承列表设置，高级版只能删除选到的列表，旗舰版可以增加删除列表（后面逻辑交给前端处理）
        boolean linkAble = FormTeamSetEnum.checkLinkAble(feeType, businessType);
        //隔离模式不放出继承列表
        if(Objects.equals(model,FormPatternEnum.FORM_ISOLATION.getModel())){
            formTeamSetLinkFormEnableVO.setLinkFormEnable(false);
        }else{
            formTeamSetLinkFormEnableVO.setLinkFormEnable(linkAble);
        }
        return formTeamSetLinkFormEnableVO;
    }

    private TeamLinkPOJO getTeamLinkPojo(PaasFormEntityExt paasFormEntityExt){
        TeamLinkPOJO teamLinkPOJO = new TeamLinkPOJO();
        teamLinkPOJO.setLinkSaasMark(paasFormEntityExt.getSaasMark());
        teamLinkPOJO.setLinkBusinessType(paasFormEntityExt.getBusinessType());
        teamLinkPOJO.setDistributorMark(paasFormEntityExt.getDistributorMark());
        teamLinkPOJO.setName(paasFormEntityExt.getBusinessName());
        return teamLinkPOJO;
    }

    private List<TeamLinkPOJO> formatLinkFormList(List<PaasFormEntityExt> paasFormEntityExts, XbbRefTypeEnum xbbRefTypeEnum, Integer saasMark, Integer distributorMark,List<Integer> linkList){
        Set<Integer> businessSet = paasFormEntityExts.stream().map(PaasFormEntityExt::getBusinessType).collect(Collectors.toSet());
        List<TeamLinkPOJO> teamLinkPOJOList = new ArrayList<>();
        for (int i = 0; i < linkList.size(); i++) {
            Integer code = linkList.get(i);
            if(businessSet.contains(code)){
                teamLinkPOJOList.add(formTeamSetHelp.getTeamLinkPojo(code,saasMark,distributorMark,i));
            }
        }
        return teamLinkPOJOList;
    }

    /**
     *
     * @Description: 过滤未开启的表单
     * @param corpid
     * @param paasFormEntityExtList 表单list
     * @return: void
     * @Author: shen.yang
     * @Date: 2022/2/23  14:25
     */
    private void filterUnenableAppAndForm(String corpid, List<PaasFormEntityExt> paasFormEntityExtList) {
        Set<Long> appIds = new HashSet<>();
        Set<Long> menuIds = new HashSet<>();
        paasFormEntityExtList.forEach(v -> {
            appIds.add(v.getAppId());
            menuIds.add(v.getMenuId());
        });

        Map<String, Object> params = new HashMap<>();
        params.put(ParameterConstant.CORPID, corpid);
        params.put(ParameterConstant.DEL, DelEnum.NORMAL.getDel());
        params.put(ParameterConstant.ENABLE, 1);
        params.put(ParameterConstant.ID_IN, appIds);
        List<PaasAppEntity> paasAppEntities = paasAppModel.findEntitys(params);

        Map<Long, PaasAppEntity> appMap = new HashMap<>();
        paasAppEntities.forEach(v -> appMap.put(v.getId(), v));

        params.put(ParameterConstant.ID_IN, menuIds);
        List<PaasMenuEntity> menuModelEntitys = paasMenuModel.findEntitys(params);

        Map<Long, PaasMenuEntity> menuMap = new HashMap<>();
        menuModelEntitys.forEach(v -> menuMap.put(v.getId(), v));

        List<Long> formIds = new ArrayList<>();
        List<Long> workOrderFormIds = new ArrayList<>();
        for (PaasFormEntityExt paasFormEntityExt : paasFormEntityExtList) {
            if (appMap.isEmpty() || menuMap.isEmpty()) {
                continue;
            }

            if (appMap.containsKey(paasFormEntityExt.getAppId()) && menuMap.containsKey(paasFormEntityExt.getMenuId())) {
                if (Objects.equals(XbbRefTypeEnum.WORK_ORDER.getCode(), paasFormEntityExt.getBusinessType())) {
                    workOrderFormIds.add(paasFormEntityExt.getId());
                } else {
                    formIds.add(paasFormEntityExt.getId());
                }
            }
        }

        Map<Long, PaasFormEntityExt> formMap = new HashMap<>();
        Map<Long, WorkOrderFormEntity> workOrderFormMap = new HashMap<>();
        if (CollectionsUtil.isNotEmpty(formIds)) {
            params.clear();
            params.put(ParameterConstant.CORPID, corpid);
            params.put(ParameterConstant.DEL, DelEnum.NORMAL.getDel());
            params.put(ParameterConstant.ID_IN, formIds);
            params.put(ParameterConstant.ENABLE, 1);
            List<PaasFormEntityExt> paasFormEntityExts = paasFormModel.findEntitys(params);
            if (CollectionsUtil.isNotEmpty(paasFormEntityExts)) {
                paasFormEntityExts.forEach(v -> formMap.put(v.getId(), v));
            }
        }

        if (CollectionsUtil.isNotEmpty(workOrderFormIds)) {
            List<WorkOrderFormEntity> workOrderFormEntities = workOrderFormModel.findEntitys(params);
            if (CollectionsUtil.isNotEmpty(workOrderFormEntities)) {
                workOrderFormEntities.forEach(v -> workOrderFormMap.put(v.getId(), v));
            }
        }

        Iterator<PaasFormEntityExt> iterator = paasFormEntityExtList.iterator();
        while (iterator.hasNext()) {
            PaasFormEntityExt next = iterator.next();
            if (Objects.equals(XbbRefTypeEnum.WORK_ORDER.getCode(), next.getBusinessType())) {
                WorkOrderFormEntity workOrderFormEntity = workOrderFormMap.get(next.getId());
                if (Objects.isNull(workOrderFormEntity)) {
                    iterator.remove();
                    continue;
                }
                next.setName(workOrderFormEntity.getName());
            } else {
                PaasFormEntityExt paasFormEntityExt = formMap.get(next.getId());
                if (Objects.isNull(paasFormEntityExt)) {
                    iterator.remove();
                    continue;
                }
                next.setName(paasFormEntityExt.getName());
            }
        }
    }



}
